package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.EditTextLengthUtil;
import com.wdh.kjs.util.PhonenumUtil;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by feifei on 2016/7/20.
 */
public class ForgetTradingActivity extends BaseTopActivity implements View.OnClickListener {
    private EditText set_tradePwd_phone;
    private EditText set_tradePwd;
    private EditText set_tradePwd_re;
    private EditText set_tradePwd_getmsg;
    private Button security_trading_password_set;
    private Button security_trading_password_reset;
    private Button set_trading_codding;
    private TimeCount time;
    private JsonModel jsonModel;
    private JsonModel_my jsonModel_my;
    private String partId;
    private Intent intent;
    private String type;
    private ImageView iv_stp_xinmima_kejian;
    private ImageView iv_stp_querenmima_kejian;
    private int xinmimatype = 0;
    private int querenmimatype = 0;
    private String nickName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_trading_password);
        SharedPreferences share = getSharedPreferences("logininfo", MODE_PRIVATE);
        partId = share.getString("loginToken", "");
        type = share.getString("type", "");
        nickName = share.getString("nickName", "");
        time = new TimeCount(60000*3, 1000);
        initview();
    }

    private void initview() {
        initTopBar("重置交易密码");
        set_tradePwd_phone = (EditText) findViewById(R.id.set_tradePwd_phone);
        set_tradePwd = (EditText) findViewById(R.id.set_tradePwd);
        set_tradePwd_re = (EditText) findViewById(R.id.set_tradePwd_re);
        set_tradePwd_getmsg = (EditText) findViewById(R.id.set_tradePwd_getmsg);
        set_trading_codding = (Button) findViewById(R.id.set_trading_codding);
        security_trading_password_set = (Button) findViewById(R.id.security_trading_password_set);
        security_trading_password_reset = (Button) findViewById(R.id.security_trading_password_reset);
        iv_stp_xinmima_kejian = (ImageView) findViewById(R.id.iv_stp_xinmima_kejian);
        iv_stp_querenmima_kejian = (ImageView) findViewById(R.id.iv_stp_querenmima_kejian);

        iv_stp_querenmima_kejian.setOnClickListener(this);
        iv_stp_xinmima_kejian.setOnClickListener(this);
        security_trading_password_set.setOnClickListener(this);
        security_trading_password_reset.setOnClickListener(this);
        set_trading_codding.setOnClickListener(this);
    }

    private void falseDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_false, null);
        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_negative.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
                set_tradePwd_phone.setText("");
                set_tradePwd.setText("");
                set_tradePwd_re.setText("");
                set_tradePwd_getmsg.setText("");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.set_trading_codding:
                if (set_tradePwd_phone.getText().toString().equals("")) {
                    falseDialogShow("请输入手机号！");
                } else if (!PhonenumUtil.isMobileNO(set_tradePwd_phone.getText().toString())) {
                    falseDialogShow("请输入正确的手机号！");
                } else {
                    time.start();
                    intcode();
                }
                break;
            case R.id.iv_stp_querenmima_kejian:
                int index=set_tradePwd_re.getSelectionStart();
                if (querenmimatype == 0) {
                    set_tradePwd_re.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    iv_stp_xinmima_kejian.setImageResource(R.drawable.visual);
                    querenmimatype = 1;
                } else {
                    set_tradePwd_re.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    iv_stp_xinmima_kejian.setImageResource(R.drawable.eye_icon);
                    querenmimatype = 0;
                }
                set_tradePwd_re.setSelection(index);
                break;
            case R.id.iv_stp_xinmima_kejian:
                int index2=set_tradePwd.getSelectionStart();
                if(xinmimatype==0){
                    set_tradePwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    xinmimatype=1;
                    iv_stp_xinmima_kejian.setImageResource(R.drawable.visual);
                }
                else if(xinmimatype==1){
                    set_tradePwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    iv_stp_xinmima_kejian.setImageResource(R.drawable.eye_icon);
                    xinmimatype=0;
                }
                set_tradePwd.setSelection(index2);
                break;
            case R.id.security_trading_password_set:
                int newPwdLength = EditTextLengthUtil.check_length(set_tradePwd.getText().toString());
                if (set_tradePwd_phone.getText().toString().equals("")) {
                    falseDialogShow("请输入手机号！");
                } else if (!PhonenumUtil.isMobileNO(set_tradePwd_phone.getText().toString())) {
                    falseDialogShow("请输入正确的手机号！");
                } else if (set_tradePwd.getText().toString().equals("")) {
                    falseDialogShow("请输入新密码！");
                } else if (newPwdLength != 0) {
                    if (newPwdLength > 0) {
                        falseDialogShow("新密码位数多于" + EditTextLengthUtil.max_length + "位");
                    } else {
                        falseDialogShow("新密码位数少于" + EditTextLengthUtil.min_length + "位");
                    }
                } else if (set_tradePwd_re.getText().toString().equals("")) {
                    falseDialogShow("请输入确认密码！");
                } else if (!set_tradePwd.getText().toString().equals(set_tradePwd_re.getText().toString())) {
                    falseDialogShow("新密码两次输入不一致！");
                } else {
                    intweb();
                }
                break;
            case R.id.security_trading_password_reset:
                set_tradePwd_phone.setText("");
                set_tradePwd.setText("");
                set_tradePwd_re.setText("");
                set_tradePwd_getmsg.setText("");
        }
    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tradePwd", set_tradePwd.getText().toString());
        params.addBodyParameter("partyId", partId);
        params.addBodyParameter("phoneNumber", set_tradePwd_phone.getText().toString());
        params.addBodyParameter("verificationCode", set_tradePwd_getmsg.getText().toString());
        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.cookieStore);
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_JIAOYI, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);


                if (jsonModel_my.getReturnMsg().equals("success")) {
                    trueDialogShow("密码重置已成功！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            intent = new Intent();
                            SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                            if (type.equals("p")) {
                                editor.putString("levels", "2");
                            } else if (type.equals("o")) {
                                editor.putString("levels", "3");
                            }
                            editor.commit();
                            finish();
                            intent.setClass(ForgetTradingActivity.this, SecuritySetting.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    }, 2000);
                } else if (jsonModel_my.getReturnMsg().equals("error")) {
                    falseDialogShow("密码重置失败！");
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(ForgetTradingActivity.this, "网络异常！");
            }
        });

    }

    private void intcode() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("phoneNumber", set_tradePwd_phone.getText().toString());
        params.addBodyParameter("sendName", nickName);
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_CODDING_Tradding, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
//                    if (jsonModel.success) {
                DefaultHttpClient dh = (DefaultHttpClient) http.getHttpClient();
                MyCookieStore.cookieStore = dh.getCookieStore();

//                    }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(ForgetTradingActivity.this, "网络异常！");
            }
        });


    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            set_trading_codding.setText("发送验证码");
            set_trading_codding.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            set_trading_codding.setClickable(false);//防止重复点击
            set_trading_codding.setText(millisUntilFinished / 1000 + "s后可重新获取");
        }
    }
}
